from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache

class AreaView(View):
    cache.get('province')
    #获取省级信息
    def get(self,request):
        province_list=cache.get('province')
        if province_list is None:
            provinces=Area.objects.filter(parent=None)
            # province_list = []
            # for province in provinces:
            #     province_list.append({
            #         'id': province.id,
            #         'name': province.name
            #     })
            province_list=[{'id':province.id,'name':province.name} for province in provinces]
            cache.set('province',province_list,24*3600)
        return JsonResponse({'code':0,'errmsg':'ok','province_list':province_list})

class SubAreaView(View):
    def get(self,request,id):
        data_list=cache.get('city:%s'%id)
        if data_list is None:
            down_level = Area.objects.filter(parent=id)
            data_list=[{'id':i.id,'name':i.name} for i in down_level]
            cache.set('city:%s'%id,data_list,3600*24)
        return JsonResponse({'code':0,'errmsg':'ok','sub_data':{'subs':data_list}})


